var mongoose = require("mongoose");
var _ = require("underscore");
var Schema = mongoose.Schema;
var ObjectID = Schema.ObjectID;
var userSchema = new Schema({
    id                 : { type: String, required: true, unique: true }
  , email              : String
  , given_name         : String
  , family_name        : String
  , keys               : [String]
  , access_token       : { type : String, required: true }
});
var User = mongoose.model('User', userSchema);
var feedSchema = new Schema({
    key                : { type: String, required: true, unique: true }
  , title              : String
  , link               : String
  , summary            : String
  , pubdate            : String
});
var Feed = mongoose.model('Feed', feedSchema);
var async = require('async');

mongoose.connect(
  'troup.mongohq.com',
  'OurRadio',
  10043,
  {user: 'zjzzjz', pass: 'zjz@dw.7980'}
);

function saveUser(accessToken, profile, done) {
  user_data = profile._json;
  user_data.access_token = accessToken;
  var user = new User(user_data);
  user.save(function(error, data){
    if(error){
        done(error);
    }
    else{
        done(null, profile);
    }
  });
}

function addKeyForUser(id, key, cb) {
   User.findOne({id: id}, function(error, user){
       if (error) {
           cb(error);
           return;
       } 
       if (user.keys.indexOf(key) <= -1) {
           user.keys.push(key);
           user.save(cb);  
       } else {
           cb(null);
       }
   });
}

function findUserByID(id, fn) {
    User.findOne({id: id}, fn);
}

function removeUserByID(id) {
  User.remove({id: id}, function(err) {
    if(err) {
      console.log("removeUserByID:" + err);
    }
  });
}

function saveFeed(feeds, cb) {
    async.each(
        feeds,
        function(item, callback) {
            var feed = new Feed(item);
            Feed.count({key: item.key}, function(err, count) {
                if (err) {
                    console.log('saveFeed:' + err);
                    callback(err);
                    return;
                } 
                if (count != 0) {
                    callback(null);
                    return;
                } 
                
                feed.save(function(error, data){
                    if(err){
                        console.log('saveFeed:' + err);
                        callback(err);
                    }
                    callback(null);
                });
            });
        },
        function(err) {
            cb(err, true);
        }
    );
}

function findFeedsByKeys(keys, fn) {
    Feed.find({ key: { $in: keys } }, fn);
}

module.exports = {
  saveUser: saveUser,
  findUserByID: findUserByID,
  removeUserByID: removeUserByID,
  saveFeed: saveFeed,
  findFeedsByKeys: findFeedsByKeys,
  addKeyForUser: addKeyForUser
}
